<script setup lang="ts">
import {
  StnCollapseSearch,
  StnResponsiveColsForm,
  useTipStore,
  TipMessageTypeConst,
} from 'st-ui-vue3-navie'
import {isNone, isStr, isEmpty} from 'st-common-core'
import {ResObjPropNameConst, ResType} from "st-common-req"

/**
 * 组件参数
 */
const {
  expandDefault = false,
  btnResponsiveWidth = 375,
  formLabelWidth = 100,
  formMaxHeight = '175px',
  formCols = '1 600:2 900:3 1200:4 1600:5',
  formAlwaysScrollbarWidth = 900,
  searchFormDefault = {},
  searchHandler = () => Promise.resolve({
    [ResObjPropNameConst.STATUS]: true,
    [ResObjPropNameConst.MESSAGE]: '获取数据成功'
  }),
} = defineProps<{
  // 默认情况下是否展开折叠面板
  expandDefault?: boolean;
  // 按钮响应式折叠收缩的屏幕宽度
  btnResponsiveWidth?: number;
  // 表单标签宽度
  formLabelWidth?: number;
  // 表单区域的最大高度
  formMaxHeight?: number | string;
  // 表单的列配置
  formCols?: number | string;
  // 表单区域一直显示滚动条的宽度
  formAlwaysScrollbarWidth?: number;
  // 搜索表单的默认值
  searchFormDefault?: Record<string, any>;
  // 搜索事件处理函数
  searchHandler?: (formData: Record<string, any>) => Promise<ResType>;
}>()

/**
 * 双向绑定数据
 */
// 搜索表单
const searchForm = defineModel<Record<string, any>>('searchForm', {default: {}})

/**
 * 搜索
 */
// 搜索表单重置按钮点击事件处理函数
const searchFormResetHandler = () => searchForm.value = {...searchFormDefault}
// 搜索表单搜索按钮点击事件处理函数
const searchFormSearchHandler = async () => {
  // 最终要提交的表单数据
  const formData = {}
  // 对表单数据预处理
  Object.entries(searchForm.value).forEach(([key, value]) => {
    // 去除字符串前后空白
    if (typeof value === 'string') value = value.trim()
    // 过滤掉空值
    if (isNone(value) || (isStr(value) && isEmpty(value))) return
    formData[key] = value
  })
  // 调用搜索事件处理函数
  const res = await searchHandler(formData)
  // 信息提示
  if (res[ResObjPropNameConst.STATUS]) useTipStore().message(res[ResObjPropNameConst.MESSAGE], TipMessageTypeConst.SUCCESS)
  else useTipStore().message(res[ResObjPropNameConst.MESSAGE], TipMessageTypeConst.ERROR)
}
</script>

<template>
  <div
    class="responsive-collapse-search box-bg rounded-lg"
    ref="responsiveCollapseSearchRef"
  >
    <StnCollapseSearch
      :expend-default="expandDefault"
      :responsive-width="btnResponsiveWidth"
      @reset="searchFormResetHandler"
      @search="searchFormSearchHandler"
      @keydown.enter.prevent="searchFormSearchHandler"
    >
      <template #default>
        <StnResponsiveColsForm
          :model="searchForm"
          :label-width="formLabelWidth"
          :max-height="formMaxHeight"
          :cols="formCols"
          :always-scrollbar-width="formAlwaysScrollbarWidth"
          :label-placement="['left', 'left']"
        >
          <slot></slot>
        </StnResponsiveColsForm>
      </template>
    </StnCollapseSearch>
  </div>
</template>

<style scoped>

</style>
